package edu.zut.jpa_demo.service.impl;

import edu.zut.jpa_demo.entity.Account;
import edu.zut.jpa_demo.repository.AccountRepository;
import edu.zut.jpa_demo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountRepository accountRepository;

    //查询账户信息
    @Override
    @Transactional(readOnly = true)
    public Account queryByName(String name) {
        return accountRepository.queryByName(name);
    }
    //转账操作
    @Override
    @Transactional(timeout = 10,isolation = Isolation.DEFAULT,
            propagation = Propagation.REQUIRED,readOnly = false)   //事务注解，可以标注在方法上或类上
    public void transfer(Account from, Account to, double money) {
        //转出
        from.setBalance(from.getBalance() - money);
        accountRepository.save(from);
        //假设在转账过程中出现了异常
//        int i = 1/0;
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //转入
        to.setBalance(to.getBalance() + money);
        accountRepository.save(to);
    }
}
